import cherrypy

from turbogears             import url 
from turbogears.identity    import current
from textile                import textile
from cgi                    import escape


def textilize(unicodeStr):
    return textile(escape(unicodeStr).encode('utf-8'), encoding='utf-8', output='utf-8')


def fmt(dt):
    '''Formats a date for pretty display on screen.'''
    return dt.strftime("%m/%d/%Y %I:%M %p")


def checkIdentity(func):
    def wrapper(*args, **kwargs):
        if current.user == None:
            redirect = cherrypy.config.get('identity.failure_url')
            raise cherrypy.HTTPRedirect(url(redirect))
        else:
            return func(*args, **kwargs)
    return wrapper

def getGroups():  
    groups = current.user.groups
    groupids = []
    for group in groups:
        groupids.append(group.groupId)
    
    return groupids

def getRecentChanges(projects, hours):
    
    recent_proj = []
    recent_issues = []
    recent_risks  = []
    recent_notes  = []
    recent_files  = []
    recent_questions = []
    recent_answers = []
    
    for project in projects:
        if len(project._new_issues(hours)) > 0:
            for issue in project._new_issues(hours):
                recent_issues.append(issue)
        if len(project._new_risks(hours)) > 0:
            for risk in project._new_risks(hours):
                recent_risks.append(risk)
        if len(project._new_notes(hours)) > 0:
            for note in project._new_notes(hours):
                recent_notes.append(note)
        if len(project._new_files(hours)) > 0:
            for file in project._new_files(hours):
                recent_files.append(file)
        if len(project._new_questions(hours)) > 0:
            for question in project._new_questions(hours):
                recent_questions.append(question)
                
        new_proj = RecentProj(project.name, project.id,
                                  recent_notes, recent_issues,
                                      recent_risks, recent_files, recent_questions)
                                              
        recent_proj.append(new_proj)
        recent_issues = []
        recent_risks = []
        recent_notes = []
        recent_files = []
        recent_questions = []
        
    return recent_proj


def sortDict(dict):
    keys = dict.keys()
    keys.sort()
    return [dict[key] for key in keys]


class RecentProj(object):
    
    def __init__(self, proj_name, proj_id, 
                     recent_notes, recent_issues, 
                     recent_risks, recent_files,
                     recent_questions):
        
        self.proj_name        =  proj_name
        self.proj_id          =  proj_id
        self.recent_notes     =  recent_notes
        self.recent_issues    =  recent_issues
        self.recent_risks     =  recent_risks
        self.recent_files     =  recent_files
        self.recent_questions =  recent_questions    